package com.zyh.controller;

import com.zyh.pojo.User;
import com.zyh.service.UserService;
import lombok.SneakyThrows;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

/**
 * 用户注册登录相关的控制器
 */
@Controller
public class UserController {
    @Autowired
    UserService userService;
    @PostMapping("/login")
    public String login(String username, String password, Model model, HttpSession session){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        try {
            subject.login(token);
            session.setAttribute("username",username);
            return "redirect:/";
        }catch (UnknownAccountException e){
            model.addAttribute("msg","用户名不存在");
            System.out.println("用户名不存在");

        }catch (Exception e){
            model.addAttribute("msg","密码错误");
            System.out.println("密码错误");

        }
        return "signup";
    }
    @GetMapping("/login")
    public String login(){
        return "signup";
    }
    @GetMapping("/logout")
    public String logout(HttpSession session){
        Subject subject=SecurityUtils.getSubject();
        if (subject.isAuthenticated()){
            session.removeAttribute("username");
            subject.logout();
        }
        return "redirect:/";
    }
    @SneakyThrows
    @PostMapping("/signup")
    public String signup(String username,String password,Model model){
        User user=userService.findByName(username);
        if(user==null){
            userService.save(username,password);
            model.addAttribute("signupmsg","注册成功快去登录吧");
        }else {
            model.addAttribute("signupmsg","用户名已存在，请更换");
        }
        return "signup";
    }

}
